package com.example.consumer;

import com.example.entity.Order;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class OrderMain1Consumer {

    @RabbitListener(queues = "order.main1.queue")
    public void handleOrder(Order order, Channel channel, Message message) throws IOException {
        // 正确地从 Message 对象中获取 deliveryTag
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String correlationId = message.getMessageProperties().getCorrelationId();

        try {
            // 业务处理
            log.info("order.main1.queue处理订单order：{}，correlationId：{}", order,correlationId);
            processOrder(order);
            // 手动确认消息（deliveryTag：消息唯一标识；multiple：是否批量确认）
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("处理订单失败: {}", order, e);
            //这里直接抛出异常，就会继续重试默认次数的，直到达到yml配置的默认次数上限
            throw new RuntimeException(e);
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);
        }
    }

    /**
     * 处理订单业务逻辑
     * @param order 订单对象
     */
    private void processOrder(Order order) {
        // 模拟订单处理逻辑
        log.info("开始处理订单，订单号：{}", order.getId());

        // 这里添加实际的业务处理逻辑
        // 例如：更新数据库、调用其他服务、发送通知等

        // 模拟处理时间
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("订单处理被中断", e);
        }

        // 模拟偶尔的处理失败
        if (order.getUserId() != null && order.getUserId().contains("ERROR")) {
            throw new RuntimeException("模拟订单处理失败");
        }

        log.info("订单处理完成，订单号：{}", order.getUserId());
    }

}